package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.domain.Announcement;
import com.tanhua.model.domain.User;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.vo.*;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.swing.text.Utilities;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class MessagesService {

    @DubboReference
    private UserApi userApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private FriendApi friendApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @DubboReference
    private UserLikeApi userLikeApi;
    @DubboReference
    private CommentApi commentApi;
    @DubboReference
    private AnnouncementApi announcementApi;
    /**
     * 根据环信id查询用户详情
     */
    public UserInfoVo findUserInfoByHuanxin(String huanxinId) {
        //1、根据环信id查询用户
        User user = userApi.findByHuanxin(huanxinId);
        //2、根据用户id查询用户详情
        UserInfo userInfo = userInfoApi.findById(user.getId());
        UserInfoVo vo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, vo); //copy同名同类型的属性
        if (userInfo.getAge() != null) {
            vo.setAge(userInfo.getAge().toString());
        }
        return vo;
    }

    //添加好友关系
    public void contacts(Long friendId) {
        //1、将好友关系注册到环信
        Boolean aBoolean = huanXinTemplate.addContact(Constants.HX_USER_PREFIX + UserHolder.getUserId(),
                Constants.HX_USER_PREFIX + friendId);
        if (!aBoolean) {
            throw new BusinessException(ErrorResult.error());
        }
        //2、如果注册成功，记录好友关系到mongodb
        friendApi.save(UserHolder.getUserId(), friendId);
    }

    //分页查询联系人列表
    public PageResult findFriends(Integer page, Integer pagesize, String keyword) {
        //1、调用API查询当前用户的好友数据 -- List<Friend>
        List<Friend> list = friendApi.findByUserId(UserHolder.getUserId(), page, pagesize);
        if (CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //2、提取数据列表中的好友id
        List<Long> userIds = CollUtil.getFieldValues(list, "friendId", Long.class);
        //3、调用UserInfoAPI查询好友的用户详情
        UserInfo info = new UserInfo();
        info.setNickname(keyword);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, info);
        //4、构造VO对象
        List<ContactVo> vos = new ArrayList<>();
        for (Friend friend : list) {
            UserInfo userInfo = map.get(friend.getFriendId());
            if (userInfo != null) {
                ContactVo vo = ContactVo.init(userInfo);
                vos.add(vo);
            }
        }
        return new PageResult(page, pagesize, 0l, vos);
    }

    /**
     * 喜欢列表
     *
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult loves(Integer page, Integer pagesize) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //根据当前用户id查询UserLike表
        List<UserLike> userLikes = userLikeApi.findById(userId);
        List<Long> userIds = new ArrayList<>();
        List<LikeVo> likeVos = new ArrayList<>();
        //判断返回值是否为空,如果为空,直接返回
        if (CollUtil.isEmpty(userLikes)) {
            return new PageResult();
        }
        //如果不为空,则获取likeUserId
        for (UserLike userLike : userLikes) {
            Long likeUserId = userLike.getUserId();
            userIds.add(likeUserId);
        }
        //遍历likeUserIds
        for (Long likeUserId : userIds) {
            //调用userInfo进行用户详情查询
            UserInfo userInfo = userInfoApi.findById(likeUserId);
            if (userInfo != null) {
                LikeVo likeVo = new LikeVo();
                likeVo.setAvatar(userInfo.getAvatar());
                Date created = userInfo.getCreated();
                likeVo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(created));
                likeVo.setId(userInfo.getId().toString());
                likeVo.setNickname(userInfo.getNickname());
                likeVos.add(likeVo);
            }
        }
        return new PageResult(page, pagesize, Long.valueOf(likeVos.size()), likeVos);
    }

    /**
     * 点赞列表
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult likes(Integer page, Integer pagesize) {
        //获取当前用户Id
        Long userId = UserHolder.getUserId();
        //根据userId查询comment表
        List<Comment> list = commentApi.findByPublishUserId(userId, CommentType.LIKE);
        List<CommentVo> commentVos = new ArrayList<>();
        //判断list是否为空
        if (CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //如果不为空,则根据list表查询userId
        for (Comment comment : list) {
            Long commentUserId = comment.getUserId();
            UserInfo userInfo = userInfoApi.findById(commentUserId);
            CommentVo commentVo = CommentVo.init(userInfo, comment);
            commentVos.add(commentVo);
        }
        return new PageResult(page,pagesize,Long.valueOf(commentVos.size()),commentVos);
    }

    /**
     * 评论列表
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult comments(Integer page, Integer pagesize) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        List<Comment> byPublishUserId = commentApi.findByPublishUserId(userId, CommentType.COMMENT);
        List<CommentVo> commentVoList = new ArrayList<>();
        //判断byPublishUserId是否为空
        if (CollUtil.isEmpty(byPublishUserId)) {
            return new PageResult();
        }
        //如果不为空,则遍历获得userId
        for (Comment comment : byPublishUserId) {
            Long userId1 = comment.getUserId();
            //调用userInfo进行用户详情查询
            UserInfo userInfo = userInfoApi.findById(userId1);
            commentVoList.add(CommentVo.init(userInfo,comment));
        }
        return new PageResult(page,pagesize,Long.valueOf(commentVoList.size()),commentVoList);
    }

    /**
     * 公告列表
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult announcements(Integer page, Integer pagesize) {

        //调用api查询Announcement表
        List<Announcement> list = announcementApi.find();
        List<AnnouncementVo> announcementVos = new ArrayList<>();
        //判断list是否为空
        if (CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //遍历list
        for (Announcement announcement : list) {
            AnnouncementVo announcementVo = new AnnouncementVo();
            BeanUtils.copyProperties(announcement,announcementVo);
            announcementVo.setId(announcement.getId().toString());
            Date created = announcement.getCreated();
            announcementVo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(created));
            announcementVos.add(announcementVo);
        }
        return new PageResult(page,pagesize,Long.valueOf(announcementVos.size()),announcementVos);
    }
}
